<?php
/**
 * Copyright (c) 2006-2008, Julien PORTALIER
 * 
 * Licensed under The LGPL License
 * Redistributions of files must retain the above copyright notice.
 * 
 * @copyright    Copyright (c) 2006-2008, Julien PORTALIER
 * @link         http://feather-cm.googlecode.com/
 * @license      http://www.opensource.org/licenses/lgpl-license.php The LGPL License
 */

class LockerComponent
{
	protected $controller;
	protected $file;
	protected $md5;
	public    $prefix;
	
	function startup(Controller $controller)
	{
		$this->controller = $controller;
	}
	
	function set($resource)
	{
		$this->md5  = md5(empty($this->prefix) ? $resource : "{$this->prefix}.$resource");
		$this->file = APP.'tmp'.DS.'locks'.DS.$this->md5;
	}
	
	function check($resource=null)
	{
		if (!is_null($resource))
			$this->set($resource);
		
		# is resource locked?
		if (file_exists($this->file))
		{
			# is lock valid?
			if (filemtime($this->file) - strtotime('+10 minutes') > 0)
				return (file_get_contents($this->file) == $this->controller->Auth->id);
			
			# lock has expired
			$this->unlock();
		}
		
		return true;
	}
	
	function lock($resource=null, $mesg=null)
	{
		if (!is_null($resource))
			$this->set($resource);
		
		if ($this->check())
		{
			# locks resource
			file_put_contents($this->file, $this->controller->Auth->id);
		}
		else
		{
			# resource is already locked
			$referer = HTTP::getReferer();
			
			if (!$this->controller->Auth->checkReferer($referer))
				$referer = '/';
			
			$this->controller->flash(
				empty($mesg) ? _('Someone is already editing this resource, please try again later.') : $mesg,
				$referer, 'warning'
			);
		}
	}
	
	function unlock($resource=null)
	{
		if (!is_null($resource))
			$this->set($resource);
		@unlink($this->file);
	}
}
?>